using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

using Atomic.Libraries;
using Atomic.Structures;
using Atomic.Vasp;

namespace Atomic.Interfaces
{
	/// <summary>
	/// Uses VESTA to visualize structures.
	/// </summary>
	public static class Vesta
	{
		// Download VESTA here:
		//
		// http://jp-minerals.org/vesta/en/download.html
		// http://www.geocities.jp/kmo_mma/crystal/download/VESTA-x86_64.tar.bz2
		//
		// Extract and install by:
		//
		// cd ~/local
		// wget http://www.geocities.jp/kmo_mma/crystal/download/VESTA-x86_64.tar.bz2
		// tar -xjvf VESTA-x86_64.tar.bz2
		// mv VESTA-x86_64 vesta
		// 
		// Make sure it's added to PATH by added the following to ~/.bashrc:
		//
		// export PATH=$HOME/local/vesta:$PATH

		/// <summary>
		/// Shows a structure using VESTA.
		/// </summary>
		public static void ShowStructure(Structure structure)
		{
			ShowStructure(new Structure[] { structure });
		}

		/// <summary>
		/// Shows the structure by opening VESTA.
		/// </summary>
		public static void ShowStructure(IEnumerable<Structure> structures)
		{
			List<string> fileNames = new List<string>();

			using (TempDirectory temp = new TempDirectory())
			{
				int i = 1;
				foreach (Structure structure in structures)
				{
					// Use the POSCAR format with ".vasp" appended to indicate the format to VESTA.
					FileInfo file = new FileInfo(Path.Combine(temp.Directory.FullName, i.ToString() + ".vasp"));
					VaspPoscar.Write(structure, file);
					fileNames.Add(file.FullName);
					i++;
				}

				Process p = new Process();
				p.StartInfo.UseShellExecute = false;
				p.StartInfo.RedirectStandardError = true;
				p.StartInfo.FileName = "VESTA";
				p.StartInfo.WorkingDirectory = temp.Directory.FullName;
				p.StartInfo.Arguments = string.Join(" ", fileNames);
				p.Start();
				p.WaitForExit();

				if (p.ExitCode != 0)
				{
					throw new Exception("Failed running VESTA. Make sure it's installed and added to PATH.");
				}
			}
		}
	}
}
